# -*- coding: utf-8 -*-
from rest_framework import serializers
from core.serializers import CustomModelSerializer
from core.relations import (
    BaseNameWritableRelatedField,
    BaseCaseNameWritableRelatedField,
    UserNameWritableRelatedField,
)
from apps.tms.models import Bug
from apps.tms.testcase.serializers import TestCaseTreeSelectSerializer
from .models import Requirement
from apps.sys.models import DictData


class ListRequirementSerializer(CustomModelSerializer):
    """
    产品需求-列表序列化器
    """

    product_name = serializers.CharField(read_only=True, source="product.name")
    module_name = serializers.CharField(read_only=True, source="module.name")
    owner_name = serializers.CharField(read_only=True, source="owner.name")
    bugs_count = serializers.SerializerMethodField()
    cases_count = serializers.SerializerMethodField()

    def get_cases_count(self, instance):
        return len(instance.testcase_set.all())

    def get_bugs_count(self, instance):
        related_bugs = set()
        for related_case in instance.testcase_set.all():
            for related_bug in related_case.bug_set.all():
                related_bugs.add(related_bug)
        return len(related_bugs)

    class Meta:
        model = Requirement
        fields = "__all__"
        read_only_fields = ["id"]


class CreateUpdateRequirementSerializer(CustomModelSerializer):
    """
    产品需求-新增、修改序列化器
    """

    product = BaseNameWritableRelatedField()
    parent = BaseNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )
    module = BaseNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )
    version = BaseNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )
    owner = UserNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )
    reviewers = UserNameWritableRelatedField(many=True)
    testcase_set = BaseNameWritableRelatedField(
        many=True, required=False, allow_empty=True, allow_null=True
    )

    class Meta:
        model = Requirement
        fields = "__all__"
        read_only_fields = ["id"]


class RequirementSerializer(CustomModelSerializer):
    """
    产品需求-查询序列化器
    """

    product = BaseNameWritableRelatedField()
    parent = BaseNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )
    module = BaseNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )
    version = BaseNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )
    owner = UserNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )
    reviewers = UserNameWritableRelatedField(many=True)
    testcase_set = BaseCaseNameWritableRelatedField(
        many=True, required=False, allow_empty=True, allow_null=True
    )
    bugs = serializers.SerializerMethodField()

    def get_bugs(self, instance):
        related_bugs = set()
        for related_case in instance.testcase_set.all():
            for related_bug in related_case.bug_set.all():
                related_bugs.add(related_bug)
        related_bugs_serializer = RequirementBugSerializer(related_bugs, many=True)
        return related_bugs_serializer.data

    class Meta:
        model = Requirement
        fields = "__all__"
        read_only_fields = ["id"]


class RequirementBugSerializer(CustomModelSerializer):
    """
    产品需求-关联缺陷序列化器
    """

    number = serializers.SerializerMethodField(read_only=True)

    def get_number(self, instance):
        gravity_lable = DictData.objects.get(
            type="sys_gravity_level", value=instance.gravity
        ).label
        return f"【{gravity_lable}】 【{instance.number}】{instance.name}"

    class Meta:
        model = Bug
        fields = ("id", "number")


class RequirementTreeSelectSerializer(CustomModelSerializer):
    """
    产品需求-树型菜单序列化器
    """

    name = serializers.SerializerMethodField(read_only=True)
    type = serializers.SerializerMethodField(read_only=True)
    children = serializers.SerializerMethodField(read_only=True)

    def get_name(self, instance):
        priority_lable = DictData.objects.get(
            type="sys_priority_level", value=instance.priority
        ).label
        return f"【{priority_lable}】{instance.name}"

    def get_type(self, instance):
        return instance._meta.object_name

    def get_children(self, instance):
        children = []
        if self.request.query_params.get("showcase") == "true":
            queryset = instance.testcase_set.filter(status="0")
            children = TestCaseTreeSelectSerializer(
                queryset, many=True, request=self.request
            ).data
        return children

    class Meta:
        model = Requirement
        fields = ["id", "name", "type", "parent", "children"]
        read_only_fields = ["id"]
